import pandas as pd
from tkinter import filedialog, messagebox


class InventoryManagement:
    def __init__(self):
        self.inventory_file = 'inventory.xlsx'
        self.inventory_df = pd.DataFrame(columns=['商品编码', '商品名称', '商品单位', '零售价', '商品规格', '扩展信息'])
        self.load_inventory()

    def load_inventory(self):
        try:
            self.inventory_df = pd.read_excel(self.inventory_file)
        except FileNotFoundError:
            self.inventory_df = pd.DataFrame(
                columns=['商品编码', '商品名称', '商品单位', '零售价', '商品规格', '扩展信息'])
            self.save_inventory()

    def save_inventory(self):
        self.inventory_df.to_excel(self.inventory_file, index=False)

    def add_item(self, item_code, item_name, unit, retail_price, specification, additional_info):
        new_item = {'商品编码': item_code, '商品名称': item_name, '商品单位': unit, '零售价': retail_price,
                    '商品规格': specification, '扩展信息': additional_info}
        new_item_df = pd.DataFrame([new_item])
        self.inventory_df = pd.concat([self.inventory_df, new_item_df], ignore_index=True)
        self.save_inventory()

    def update_item(self, item_code, **kwargs):
        if item_code in self.inventory_df['商品编码'].values:
            self.inventory_df.loc[self.inventory_df['商品编码'] == item_code, kwargs.keys()] = kwargs.values()
            self.save_inventory()
            return True, "物品更新成功"
        else:
            return False, "商品编码不存在"

    def delete_item(self, item_code):
        if item_code in self.inventory_df['商品编码'].values:
            self.inventory_df = self.inventory_df[self.inventory_df['商品编码'] != item_code]
            self.save_inventory()
            return True, "物品删除成功"
        else:
            return False, "商品编码不存在"

    def get_items(self):
        self.load_inventory()
        return self.inventory_df.to_dict(orient='records')

    def import_items(self):
        file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
        if file_path:
            try:
                imported_df = pd.read_excel(file_path)
                required_columns = ['商品编码', '商品名称', '商品单位', '零售价', '商品规格', '扩展信息']
                missing_columns = [col for col in required_columns if col not in imported_df.columns]

                if missing_columns:
                    raise ValueError(f"导入的文件缺少必要的列: {', '.join(missing_columns)}")

                self.inventory_df = pd.concat([self.inventory_df, imported_df], ignore_index=True)
                self.save_inventory()
                return True, "数据导入成功"
            except ValueError as ve:
                return False, str(ve)
            except Exception as e:
                return False, f"数据导入失败: {str(e)}"
        else:
            return False, "未选择文件"